﻿using MahApps.Metro.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using Microsoft.Win32;
using KELT.KELTObjects;
using KELT.Viewport;
using KELT.Files;
using KELT.DragDropFramework.DragDropFrameworkData;
using KELT.DragDropFramework;
using KELT.KELTObjects.LibraryObjectModel;
using System.IO;
using KELT.Animation.AnimationEffect;
using KELT.Animation.Animation2D;

using KELT.Controls.Timeline.TimelineChart;
using System.Windows.Media.Media3D;
using KELT.Animation.Animation3D;
using System.Threading;
using KELT.AutoColor;
using KELT.AutoText;

using KELT.Controls.Page;

namespace KELT
{
    /// <summary>
    /// TOOL.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class TOOL : MetroWindow
    {
        private OpenFileDialog imagedlg;    // 이미지 다이얼로그
        private OpenFileDialog sounddlg;    // 사운드 다이얼로그
        private OpenFileDialog textdlg;     // 텍스트 다이얼로그

        private ObjManager objmgr;           // 오브젝트 매니저
        public CameraManager cameraManager; // 카메라 매니저
        public ViewPortMgr viewPortMgr; // viewportobj 매니저

        public FileKELT currentKELTFile = null;
        public KELTFileControl keltFileControl = new KELTFileControl();


        public SoundManager soundManager;
        private EncoderManager encoderManager;

        public TOOL()
        {
            InitializeComponent();

            init();
            DragAndDropInit();

            Application.Current.MainWindow = this;

            if (currentKELTFile == null)
            {
                // KELT 파일 이 없을 시 새로 프로젝트 만드는 창 띄울 것
                currentKELTFile = keltFileControl.makeProject(this, new FileKELT());
                // 나중에 이거 코드 새 프로젝트 다이얼로그로 옮길 것.
            }
            else
            {
                // KELT 파일을 로딩 할 것.

            }

            // Data Provider
            ListBoxDataProvider<ListBox, ListBoxItem> ListBoxDataProvider =
                new ListBoxDataProvider<ListBox, ListBoxItem>("ListBoxItemObject");

            // Data Consumer
            ListBoxDataConsumer<ListBox, ListBoxItem> ListBoxDataConsumer =
                new ListBoxDataConsumer<ListBox, ListBoxItem>(new string[] { "ListBoxItemObject" });

            // Data Provider
            ListBoxDataProvider<ListBox, ItemPageControl> ItemPageDataProvider =
                new ListBoxDataProvider<ListBox, ItemPageControl>("ListBoxItemPage");

            // Data Consumer
            ListBoxDataConsumer<ListBox, ItemPageControl> ItemPageDataConsumer =
                new ListBoxDataConsumer<ListBox, ItemPageControl>(new string[] { "ListBoxItemPage" });


            // Drag Managers
            DragManager dragHelperListBox0 = new DragManager(this.panel_page, 
                new IDataProvider[] {
                    ItemPageDataProvider,
                    ListBoxDataProvider
                });

            // Drop Managers
            DropManager dropHelperListBox0 = new DropManager(this.panel_page,
                new IDataConsumer[] {
                    ItemPageDataConsumer,
                    ListBoxDataConsumer
                });

            //// Drag And Drop Framework
            //CanvasDataProvider<Canvas, ChartAnimationObject> canvasChartAnimationObjectDataProvider =
            //    new CanvasDataProvider<Canvas, ChartAnimationObject>("CanvasChartAnimationObject");

            //CanvasDataConsumer<Canvas, ChartAnimationObject> canvasChartAnimationObjectDataConsumer =
            //    new CanvasDataConsumer<Canvas, ChartAnimationObject>(new string[] { "CanvasChartAnimationObject" });

            //// Drag Managers
            //DragManager dragHelperCanvas0 = new DragManager(this.canvas0,
            //    new IDataProvider[] {
            //        canvasChartAnimationObjectDataProvider
            //    });

            //// Drop Managers
            //DropManager dropHelperCanvas0 = new DropManager(this.canvas0,
            //    new IDataConsumer[] {
            //        canvasChartAnimationObjectDataConsumer
            //    });

        }

        public void init()
        {
            this.Loaded += TOOL_Loaded;

            // window position


            // object manager 할당
            objmgr = (ObjManager)Application.Current.FindResource("ObjectManager");

            viewPortMgr = (ViewPortMgr)Application.Current.FindResource("ViewportMgr");
            viewPortMgr.SetMainContext(this);

            cameraManager = (CameraManager)Application.Current.FindResource("CameraManager");
            cameraManager.init(this);
            // slider 
            this.slider_imagesize.Maximum = 250;
            this.slider_imagesize.Minimum = 50;
            this.slider_imagesize.Value = 250;

            // 카메라 전환 효과 창

            soundManager = new SoundManager();
            encoderManager = new EncoderManager(this);

        }
        public void DragAndDropInit()
        {


            //test DragAndDrop
            // Data Provider
            ListBoxDataProvider<ListBox, ListBoxItem> listBoxDataProvider =
                new ListBoxDataProvider<ListBox, ListBoxItem>("ListBoxItemObject");

            // Data Consumer
            ListBoxDataConsumer<ListBox, ListBoxItem> listBoxDataConsumer =
                new ListBoxDataConsumer<ListBox, ListBoxItem>(new string[] { "ListBoxItemObject" });

            // Data Consumer of TreeViewItems
            TreeViewItemToListBoxItem<ItemsControl, TreeViewItem> treeViewItemToListBoxItem =
                new TreeViewItemToListBoxItem<ItemsControl, TreeViewItem>(new string[] { "TreeViewItemObject" });

            // Drag Managers
            DragManager dragHelperListBox0 = new DragManager(this.listbox_text, listBoxDataProvider);

            // Drop Managers
            DropManager dropHelperListBox0 = new DropManager(this.listbox_text,
                new IDataConsumer[] {
                    listBoxDataConsumer,
                    treeViewItemToListBoxItem,
                });

        }

        void TOOL_Loaded(object sender, RoutedEventArgs e)
        {
            this.Top = 0;
            this.Left = 0;

            this.grid_topmenu.Visibility = Visibility.Hidden;

            this.popup_2d.IsOpen = false;
            this.popup_3d.IsOpen = false;
            this.popup_effect.IsOpen = false;
            this.popup_import.IsOpen = false;

            this.check_move.IsChecked = true;

            this.grid_newpageoption.Visibility = Visibility.Hidden;
            this.grid_property.Visibility = Visibility.Hidden;

            cameraManager.CreatePage();
            cameraManager.pageList.ElementAt(cameraManager.pageList.Count - 1).isAuto = false;
            cameraManager.pageList.ElementAt(cameraManager.pageList.Count - 1).selectNum = 0;
            cameraManager.pageList.ElementAt(cameraManager.pageList.Count - 1).isSet = true;

        }


        #region 상미추가-버튼모음
        private void btn_topmenuopen_Click(object sender, RoutedEventArgs e)
        {
            // topmenu open btn 활성화
            this.panel_topmenuopen.Visibility = Visibility.Hidden;
            this.grid_topmenu.Visibility = Visibility.Visible;
        }

        private void btn_topmenuclose_Click(object sender, RoutedEventArgs e)
        {
            // topmenu cloase btn 활성화
            this.grid_topmenu.Visibility = Visibility.Hidden;
            this.panel_topmenuopen.Visibility = Visibility.Visible;
        }

        private void btn_2dani_Click(object sender, RoutedEventArgs e)
        {
            // 2d animation btn

            this.popup_2d.IsOpen = true;
            this.popup_3d.IsOpen = false;
            this.popup_effect.IsOpen = false;
            this.popup_import.IsOpen = false;
        }

        private void btn_3dani_Click(object sender, RoutedEventArgs e)
        {
            // 3d animation btn
            this.popup_2d.IsOpen = false;
            this.popup_3d.IsOpen = true;
            this.popup_effect.IsOpen = false;
            this.popup_import.IsOpen = false;
        }

        private void btn_effect_Click(object sender, RoutedEventArgs e)
        {
            // effect btn
            this.popup_2d.IsOpen = false;
            this.popup_3d.IsOpen = false;
            this.popup_effect.IsOpen = true;
            this.popup_import.IsOpen = false;
        }

        private void btn_import_Click(object sender, RoutedEventArgs e)
        {
            // import btn
            this.popup_2d.IsOpen = false;
            this.popup_3d.IsOpen = false;
            this.popup_effect.IsOpen = false;
            this.popup_import.IsOpen = true;
        }

        #region 등장

        private void btn_flyinleft_Click(object sender, RoutedEventArgs e)
        {
            // 2d ani fly in left
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                FlyAppearAnimation flyAppear = new FlyAppearAnimation();
                flyAppear.setOption(0);
                viewPortMgr.ObjectAnimationRegist(flyAppear, i);

            }

        }
        private void btn_flyinright_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                FlyAppearAnimation flyAppear = new FlyAppearAnimation();
                flyAppear.setOption(1);
                viewPortMgr.ObjectAnimationRegist(flyAppear, i);

            }
        }


        private void btn_rise_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                FlyAppearAnimation flyAppear = new FlyAppearAnimation();
                flyAppear.setOption(2);
                viewPortMgr.ObjectAnimationRegist(flyAppear, i);

            }
        }
        private void btn_down_Click(object sender, RoutedEventArgs e)
        {
            // 2d ani down
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                FlyAppearAnimation flyAppear = new FlyAppearAnimation();
                flyAppear.setOption(3);
                viewPortMgr.ObjectAnimationRegist(flyAppear, i);

            }
        }


        private void btn_bouncein_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani bouncein
                BounceAnimation bounce = new BounceAnimation();
                viewPortMgr.ObjectAnimationRegist(bounce, i);

            }
        }

        private void btn_brightin_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {

                viewPortMgr.ObjectAnimationRegist(new OpacityApearAnimation(), i);

            }
            // 2d ani brightin
        }


        #endregion

        #region 퇴장


        private void btn_flyoutright_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani fly out right
                FlyDisAppearAnimation flyAppear2 = new FlyDisAppearAnimation();
                flyAppear2.setOption(0);
                viewPortMgr.ObjectAnimationRegist(flyAppear2, i);
            }
        }
        private void btn_flyoutleft_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani fly out left
                FlyDisAppearAnimation flyAppear2 = new FlyDisAppearAnimation();
                flyAppear2.setOption(1);
                viewPortMgr.ObjectAnimationRegist(flyAppear2, i);
            }
        }
        private void btn_outdown_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani fall out
                FlyDisAppearAnimation flyAppear2 = new FlyDisAppearAnimation();
                flyAppear2.setOption(2);
                viewPortMgr.ObjectAnimationRegist(flyAppear2, i);
            }
        }

        private void btn_outup_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani fise out
                FlyDisAppearAnimation flyAppear2 = new FlyDisAppearAnimation();
                flyAppear2.setOption(3);
                viewPortMgr.ObjectAnimationRegist(flyAppear2, i);
            }
        }

        private void btn_bounceout_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani bounceout
                BounceOutAnimation bounce = new BounceOutAnimation();
                viewPortMgr.ObjectAnimationRegist(bounce, i);
            }
        }

        private void btn_brightout_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani brightout
                viewPortMgr.ObjectAnimationRegist(new OpacityDisappearAnimation(), i);
            }
        }
        #endregion


        #region 강조

        private void btn_color_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {

                // 2d ani color
                ColorAni color = new ColorAni();
                viewPortMgr.ObjectAnimationRegist(color, i);

            }
        }

        private void btn_highlight_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani color
                PulseAnimation pulse = new PulseAnimation();
                viewPortMgr.ObjectAnimationRegist(pulse, i);

            }
        }

        private void btn_rotate_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani rotate
                Rot2DAnimation rotate = new Rot2DAnimation();
                viewPortMgr.ObjectAnimationRegist(rotate, i);

            }
        }

        private void btn_tilt_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 2d ani tilt
                ShakeAnimation qu = new ShakeAnimation();
                qu.setOption(20);
                viewPortMgr.ObjectAnimationRegist(qu, i);

            }
        }

        private void btn_mask_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {

                // 2d ani mask
                MaskAnimation mask = new MaskAnimation();
                viewPortMgr.changeOpacityMask();
                viewPortMgr.ObjectAnimationRegist(mask, i);
            }
        }
        #endregion

        #region 3D

        private void btn_3drotate_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 3d ani rotate
                Rot3DAnimation rotate3d = new Rot3DAnimation();
                rotate3d.setOption(1);
                viewPortMgr.ObjectAnimationRegist(rotate3d, i);
            }

        }

        private void btn_3dflyin_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 3d ani flyin
                FlyAppearAnimation fly3D = new FlyAppearAnimation();
                fly3D.setOption(4);
                viewPortMgr.ObjectAnimationRegist(fly3D, i);
            }
        }

        private void btn_3dflyout_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 3d ani flyout
                FlyAppearAnimation fly3D = new FlyAppearAnimation();
                fly3D.setOption(5);
                viewPortMgr.ObjectAnimationRegist(fly3D, i);
            }
        }

        private void btn_3dzoomin_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 3d ani zoomin
                ZoomAnimation zoom = new ZoomAnimation();
                zoom.setOption(1, 2);
                viewPortMgr.ObjectAnimationRegist(zoom, i);
            }
        }

        private void btn_3dzoomout_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < viewPortMgr.selectList.Count; i++)
            {
                // 3d ani zoomout
                ZoomAnimation zoom = new ZoomAnimation();
                zoom.setOption(1, 0.5);
                viewPortMgr.ObjectAnimationRegist(zoom, i);
            }
        }


        #endregion

        private void btn_zoomin_Click(object sender, RoutedEventArgs e)
        {
            // zoomin btn
            cameraManager.CameraZoomIn();
        }

        private void btn_zoomout_Click(object sender, RoutedEventArgs e)
        {
            // zoomout btn
            cameraManager.CameraZoomOut();
        }

        private string returnTextString()
        {
            // text load btn
            this.popup_import.IsOpen = false;
            textdlg = new OpenFileDialog();

            textdlg.Multiselect = true;
            textdlg.Filter = "text file(*.txt) | *.txt";
            textdlg.DefaultExt = "txt";
            textdlg.Title = "Text Files to choose from.";
            bool? res = textdlg.ShowDialog();
            string text = "";

            if (res.HasValue && res.Value)
            {
                foreach (string str in textdlg.FileNames)
                {
                    using (StreamReader sr = new StreamReader(str, System.Text.Encoding.Default))
                    {
                        text += sr.ReadToEnd();
                        text += '\n';
                    }
                }
            }
            return text;
        }
        private void btn_effectrain_Click(object sender, RoutedEventArgs e)
        {
            double endTime = 0;
            for (int i = 0; i < viewPortMgr.ObjectList.Count; i++)
            {
                if (endTime < viewPortMgr.ObjectList.ElementAt(i).endTime)
                {
                    endTime = viewPortMgr.ObjectList.ElementAt(i).endTime;
                }
            }
            double width = (mainViewport.RenderSize.Width / 2) - 50;
            double height = mainViewport.RenderSize.Height / 2;


            // effect rain
            this.popup_effect.IsOpen = false;
            viewPortMgr.CreateParticleObject(returnTextString(), width, height, endTime, endTime + 10, 0);


        }

        private void btn_effectrotate_Click(object sender, RoutedEventArgs e)
        {
            double endTime = 0;
            for (int i = 0; i < viewPortMgr.ObjectList.Count; i++)
            {
                if (endTime < viewPortMgr.ObjectList.ElementAt(i).endTime)
                {
                    endTime = viewPortMgr.ObjectList.ElementAt(i).endTime;
                }
            }
            double width = mainViewport.RenderSize.Width / 2;
            double height = mainViewport.RenderSize.Height / 2;
            // effect rain
            this.popup_effect.IsOpen = false;
            viewPortMgr.CreateParticleObject(returnTextString(), width, height, endTime, endTime + 10, 1);

        }

        private void btn_effectspread_Click(object sender, RoutedEventArgs e)
        {
            double endTime = 0;
            for (int i = 0; i < viewPortMgr.ObjectList.Count; i++)
            {
                if (endTime < viewPortMgr.ObjectList.ElementAt(i).endTime)
                {
                    endTime = viewPortMgr.ObjectList.ElementAt(i).endTime;
                }
            }

            double width = mainViewport.RenderSize.Width / 2;
            double height = mainViewport.RenderSize.Height / 2;

            // effect rain
            this.popup_effect.IsOpen = false;
            viewPortMgr.CreateParticleObject(returnTextString(), width, height, endTime, endTime + 10, 2);

        }

        private void btn_effectwind_Click(object sender, RoutedEventArgs e)
        {
            // effect wind

            double endTime = 0;
            for (int i = 0; i < viewPortMgr.ObjectList.Count; i++)
            {
                if (endTime < viewPortMgr.ObjectList.ElementAt(i).endTime)
                {
                    endTime = viewPortMgr.ObjectList.ElementAt(i).endTime;
                }
            }
            double width = mainViewport.RenderSize.Width / 2;
            double height = mainViewport.RenderSize.Height / 2;
            // effect rain
            this.popup_effect.IsOpen = false;
            viewPortMgr.CreateParticleObject(returnTextString(), width, height, endTime, endTime + 10, 3);

        }





        private void btn_effectcamera_Click(object sender, RoutedEventArgs e)
        {
            // effect camera
            this.popup_effect.IsOpen = false;

            AutoColorWindow autoColorWindow = new AutoColorWindow(this);
            autoColorWindow.Show();

        }

        private void btn_backGround(object sender, RoutedEventArgs e)
        {
            // effect font color

        }

        private void btn_effectcolorchange_Click(object sender, RoutedEventArgs e)
        {
            // effect font color
            this.popup_effect.IsOpen = false;
            ColorPickerWindow pickerWindow = new ColorPickerWindow(this);
            pickerWindow.Show();

        }

        private void btn_effectfont_Click(object sender, RoutedEventArgs e)
        {
            // effect font
            this.popup_effect.IsOpen = false;

            // effect font color
            AutoTextWindow autoTextWindow = new AutoTextWindow(this);
            autoTextWindow.Show();

        }


        private void btn_page_Click(object sender, RoutedEventArgs e)
        {
            // page plus btn
            this.grid_newpageoption.Visibility = Visibility.Visible;
            Page page = cameraManager.CreatePage();

            DrawingVisual drawingVisual = new DrawingVisual();
            DrawingContext drawingContext = drawingVisual.RenderOpen();

            drawingContext.DrawRectangle(new VisualBrush(this.EncoderWindow), null, new Rect(new Point(0, 0), new Point(this.EncoderWindow.ActualWidth, this.EncoderWindow.ActualHeight)));
            drawingContext.Close();

            RenderTargetBitmap target = new RenderTargetBitmap((int)this.EncoderWindow.ActualWidth, (int)this.EncoderWindow.ActualHeight, 96, 96, System.Windows.Media.PixelFormats.Pbgra32);
            target.Render(drawingVisual);

            
            page.img.Source = target;
            //img.Margin = new Thickness(10);

            page.img.MouseLeftButtonDown += img_MouseLeftButtonDown;

            //this.panel_page.Children.Add(img);
        }

        void img_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            //for (int i = 0; i < panel_page.Children.Count; i++)
            //{

            //}
        }

        public void previewDown_page(object sender, MouseButtonEventArgs e)
        {


            //cameraManager.moveCameraAnimation(cameraManager.pageList.IndexOf(sender as Page));
        }

        private void btn_imageload_Click(object sender, RoutedEventArgs e)
        {
            // image load btn
            this.popup_import.IsOpen = false;
            imagedlg = new OpenFileDialog();

            imagedlg.Multiselect = true;
            imagedlg.Filter = "image file(*.png) | *.png";
            imagedlg.DefaultExt = "png";
            imagedlg.Title = "Please select a image file.";
            bool? res = imagedlg.ShowDialog();

            if (res.HasValue && res.Value)
            {
                foreach (string str in imagedlg.FileNames)
                {
                    KELT_OBJ obj = new ImageObj();

                    if (obj is ImageObj)
                    {
                        objmgr.CreateImageObj(str, obj, 0, 0, 0, 0, 0, 0, "none");
                    }

                }
            }
        }

        private void btn_soundload_Click(object sender, RoutedEventArgs e)
        {
            // sound load btn
            this.popup_import.IsOpen = false;
            sounddlg = new OpenFileDialog();

            sounddlg.Multiselect = true;
            sounddlg.Filter = "sound file(*.mp3) | *.mp3";
            sounddlg.DefaultExt = "mp3";
            sounddlg.Title = "Please select a sound file.";
            bool? res = sounddlg.ShowDialog();

            if (res.Value && res.HasValue)
            {
                foreach (string str in sounddlg.FileNames)
                {
                    KELT_OBJ obj = new SoundObj();

                    if (obj is SoundObj)
                    {
                        objmgr.CreateSoundObj(str, obj, 0, 0, 0, 0, 0, 0, "none");
                    }

                }
            }
        }

        private void btn_textload_Click(object sender, RoutedEventArgs e)
        {
            // text load btn
            this.popup_import.IsOpen = false;
            textdlg = new OpenFileDialog();

            textdlg.Multiselect = true;
            textdlg.Filter = "text file(*.txt) | *.txt";
            textdlg.DefaultExt = "txt";
            textdlg.Title = "Text Files to choose from.";
            bool? res = textdlg.ShowDialog();

            if (res.HasValue && res.Value)
            {
                foreach (string str in textdlg.FileNames)
                {
                    using (StreamReader sr = new StreamReader(str, System.Text.Encoding.Default))
                    {
                        this.textbox_text.Text += sr.ReadToEnd();
                        this.textbox_text.Text += '\n';
                    }
                }
            }
        }

        private void btn_done_Click(object sender, RoutedEventArgs e)
        {
            // import popup done
            this.popup_import.IsOpen = false;

            string str = this.textbox_text.Text;
            string[] words = str.Split(' ');
            foreach (string text in words)
            {
                string[] words2 = text.Split('\r');
                foreach (string text2 in words2)
                {
                    string[] words3 = text2.Split('\n');
                    foreach (string text3 in words3)
                    {
                        if (text3 != "")
                        {
                            // 띄어쓰기, 개행 모두 제거한 객체
                            KELT_OBJ textobj = new TextObj();
                            objmgr.CreateTextObj("직접입력", textobj, text3, 10, 0, 0, 0, 0, 0, "none");

                        }
                    }
                }
            }
            this.textbox_text.Clear();
        }

        private void btn_save_Click(object sender, RoutedEventArgs e)
        {
            // file save     
            viewPortMgr.myStoryboard.Stop(this); // stop doesn't work
            viewPortMgr.myStoryboard.Begin(this, true); // if the second parameter is missing or false, it doesn't work
            cameraManager.Start();// if the second parameter is missing or false, it doesn't work
        }

        private void btn_load_Click(object sender, RoutedEventArgs e)
        {
            // file load
        }

        private void btn_encording_Click(object sender, RoutedEventArgs e)
        {
            // encording
            viewPortMgr.unSelectObject();


            encoderManager.CaptureWindow(this.EncoderWindow);
            cameraManager.RegistCameraAnimation();

        }


        #endregion

        #region Keyboard
        private void KeyboardHandler(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                this.listbox_text.UnselectAll();
                objmgr.ClearSelectList();
                viewPortMgr.unSelectObject();
            }
            else if (e.Key == Key.Delete)
            {

                viewPortMgr.DeleteObject();
            }


            if (Keyboard.IsKeyDown(Key.LeftCtrl) && e.Key == Key.N)
            {

                viewPortMgr.resetObject();

            }

        }
        #endregion
        private void slider_imagesize_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            foreach (ImageObj img in listbox_image.Items)
            {
                img.ScaledHeight = (int)slider_imagesize.Value;
                img.ScaledWidth = (int)slider_imagesize.Value;
            }

        }



        #region 희유-마우스이벤트
        /******** 객체 마우스이벤트 **********************************/
        public void Object_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //Mouse.OverrideCursor = Cursors.Hand;
                viewPortMgr.MouseDownObject(sender, e);
                cameraManager.MouseDownObject(sender, e);

            }
            catch
            {

            }
        }

        public void Object_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                viewPortMgr.MouseMoveObject();
                cameraManager.MouseMoveObject();
            }
            catch
            {

            }
        }

        /******** 마우스휠이벤트 **********************************/
        private void MouseWheelEventHandler(object sender, MouseWheelEventArgs e)
        {
            cameraManager.CameraZoom(e.Delta);
        }

        /******** 마우스다운이벤트 **********************************/
        private void MouseDownEventHandler(object sender, MouseButtonEventArgs e)
        {
            double x = e.MouseDevice.GetPosition(mainViewport).X;
            double y = e.MouseDevice.GetPosition(mainViewport).Y;


            if (e.ChangedButton == MouseButton.Middle && e.ButtonState == MouseButtonState.Pressed)
            {
                cameraManager.MouseWheelDown(e.MouseDevice.GetPosition(mainViewport));
            }

        }

        /******** 마우스무브이벤트 **********************************/
        private void MouseMoveEventHandler(object sender, MouseEventArgs e)
        {
            try
            {
                cameraManager.MouseWheelMove(e.MouseDevice.GetPosition(mainViewport));
                viewPortMgr.ObjectRotate();
                viewPortMgr.ObjectScale();
            }
            catch
            {
            }
        }

        /******** 마우스업이벤트 **********************************/
        private void MouseUpEventHandler(object sender, MouseButtonEventArgs e)
        {
            try
            {

                cameraManager.MouseWheelUp(e.MouseDevice.GetPosition(mainViewport));
                viewPortMgr.MouseUpObject();
                cameraManager.MouseUpObject();

            }
            catch
            {

            }
        }

        private void MouseLeaveEventHandler(object sender, MouseEventArgs e)
        {
            try
            {
                cameraManager.MouseWheelUp(e.MouseDevice.GetPosition(mainViewport));
                viewPortMgr.MouseUpObject();
                cameraManager.MouseUpObject();

            }
            catch
            {

            }

        }

        #endregion


        #region 라이브러리Mouse
        private void loadimage_MouseEnter(object sender, MouseEventArgs e)
        {
            this.listbox_image.SelectedItem = (sender as Image).DataContext;
            KELT_OBJ obj = (KELT_OBJ)this.listbox_image.SelectedItem;
            //this.ttip_text = obj.FileName;
        }

        private void MetroWindow_Selected(object sender, RoutedEventArgs e)
        {

        }

        private void MetroWindow_MouseMove(object sender, MouseEventArgs e)
        {
            //double pt = (double)(e.GetPosition(this));
            //this.ttip_imagelist.HorizontalOffset = Convert.ToDouble(pt);
            //this.ttip_imagelist.VerticalOffset = Convert.ToDouble(pt);
        }

        private void loadimage_MouseMove(object sender, MouseEventArgs e)
        {
        }

        private void listbox_text_up(object sender, MouseButtonEventArgs e)
        {
            objmgr.SelectObject(listbox_text.SelectedItems);
        }

        private void listbox_image_MouseUp(object sender, MouseButtonEventArgs e)
        {
            objmgr.SelectObject(listbox_image.SelectedItems);
        }

        #endregion
        #region DragAndDrop
        private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ListBox parent = (ListBox)sender;
            ListBox dragSource = parent;
            object data = GetDataFromListBox(dragSource, e.GetPosition(parent));

            if (data != null)
            {
                DragDrop.DoDragDrop(parent, data, DragDropEffects.Move);
            }
            if (Keyboard.IsKeyDown(Key.LeftCtrl) == false)
            {
                objmgr.ClearSelectList();
            }
            objmgr.SelectObject(listbox_text.SelectedItems);
        }


        private static object GetDataFromListBox(ListBox source, Point point)
        {
            UIElement element = source.InputHitTest(point) as UIElement;
            if (element != null)
            {
                object data = DependencyProperty.UnsetValue;
                while (data == DependencyProperty.UnsetValue)
                {
                    data = source.ItemContainerGenerator.ItemFromContainer(element);
                    if (data == DependencyProperty.UnsetValue)
                    {
                        element = VisualTreeHelper.GetParent(element) as UIElement;
                    }
                    if (element == source)
                    {
                        return null;
                    }
                }
                if (data != DependencyProperty.UnsetValue)
                {
                    return data;
                }
            }
            return null;
        }


        //3D Viewport Drop Event
        private void ListBox_Drop(object sender, DragEventArgs e)
        {
            try
            {
                object data = e.Data.GetData(typeof(TextObj));
                if (data == null) data = e.Data.GetData(typeof(ImageObj));
                if (data == null) data = e.Data.GetData(typeof(SoundObj));

                Point p = e.GetPosition(this);
                string dataType = (data as KELT_OBJ).objectType;

                if (objmgr.selectList.Count <= 1)
                {
                    double startTime = cameraManager.pageList.ElementAt(cameraManager.pageList.Count - 1).endTime - 0.1;
                    double endTime = cameraManager.pageList.ElementAt(cameraManager.pageList.Count - 1).endTime + 3 - 0.1;

                    if (cameraManager.pageList.Count == 1)
                    {
                        startTime = 0; endTime = 3;
                    }
                    if (dataType == "TextObj")
                    {
                        viewPortMgr.CreateText(((TextObj)data), p.X - 250, p.Y, startTime, endTime, 1, 0, 0, 3);
                    }
                    else if (dataType == "ImageObj")
                    {
                        viewPortMgr.createPictureObject(((ImageObj)data), p.X - 250, p.Y, startTime, endTime);
                    }
                    else if (dataType == "SoundObj")
                    {
                        soundManager.selectSound = (SoundObj)data;
                    }
                    viewPortMgr.selectList.Clear();
                }
                else
                {
                    Random rand = new Random();
                    byte[] colorBytes = new byte[3];
                    viewPortMgr.CreateGroupText(objmgr.selectList, p.X - 250, p.Y, 0, 3, 1, 0, 0, 0);

                }

            }
            catch (Exception)
            {

            }
        }
        #endregion

        private void popup2d_close_Click(object sender, RoutedEventArgs e)
        {
            // 2d popup close btn
            this.popup_2d.IsOpen = false;

        }

        private void popup3d_close_Click(object sender, RoutedEventArgs e)
        {
            // 3d popup close btn
            this.popup_3d.IsOpen = false;

        }

        private void popupeffect_close_Click(object sender, RoutedEventArgs e)
        {
            // effect popup close btn
            this.popup_effect.IsOpen = false;

        }

        private void popupimport_close_Click(object sender, RoutedEventArgs e)
        {
            // effect popup close btn
            this.popup_import.IsOpen = false;

        }

        private void check_camera_Checked(object sender, RoutedEventArgs e)
        {
            // new page option camera check
        }

        private void check_move_Checked(object sender, RoutedEventArgs e)
        {
            // new page option move check
        }

        private void check_move_Unchecked(object sender, RoutedEventArgs e)
        {
            // new page option move uncheck
            this.check_camera.IsChecked = false;
        }

        private void btn_newpageoption_Click(object sender, RoutedEventArgs e)
        {
            // new page option done btn
            this.grid_newpageoption.Visibility = Visibility.Hidden;
        }

        public void EncoderWindow_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.viewPortMgr.MouseRightDownObject(sender, e);
        }

        private void btn_property_Click(object sender, RoutedEventArgs e)
        {
            // property done btn\
            this.grid_property.Visibility = Visibility.Hidden;
        }





    }
}
